window.app = angular.module('App', []);

var regexIso8601 = /\/Date\((.*?)\)\//gi;
function convertDateStringsToDates(input) {
    // Ignore things that aren't objects.
    if (typeof input !== "object") return input;

    for (var key in input) {
        if (!input.hasOwnProperty(key)) continue;

        var value = input[key];
        var match;
        // Check for string properties which look like dates.
        // TODO: Improve this regex to better match ISO 8601 date strings.
        if (typeof value === "string" && (match = value.match(regexIso8601))) {
            // Assume that Date.parse can parse ISO 8601 strings, or has been shimmed in older browsers to do so.
            var parsedDate = new Date(parseInt(value.substr(6)));

            var jsDate = new Date(parsedDate);
            input[key] = pad((jsDate.getMonth() + 1)) + '/' + pad(jsDate.getDate()) + '/' + pad(jsDate.getFullYear());

        } else if (typeof value === "object") {
            // Recurse into object
            convertDateStringsToDates(value);
        }
    }
}
function pad(d) {
    return (d < 10) ? '0' + d.toString() : d.toString();
}

//loading 
window.app.config(function ($httpProvider) {
    $httpProvider.responseInterceptors.push('myHttpInterceptor');

    var spinnerFunction = function (data, headersGetter) {
        // todo start the spinner here
        var loading = "#site_statistics_loading";

        //$(loading).show();
        return data;
    };
    //show loading 
    $httpProvider.defaults.transformRequest.push(spinnerFunction);
    //convert datetime json to normal datetime to display on form
    $httpProvider.defaults.transformResponse.push(function (responseData) {
        convertDateStringsToDates(responseData);
        return responseData;
    });
    //check session timeout
    $httpProvider.interceptors.push(['$injector',
    function ($injector) {
        return $injector.get('AuthInterceptor');
    }]);

})
    .factory('AuthInterceptor', function ($rootScope, $q) {
        return {
            responseError: function (response) {
                if (response.status === 401) {
                    //The user is not logged in
                    $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated,
                                          response);
                }
                if (response.status === 403) {
                    //The user is logged in but isn’t allowed access
                    $rootScope.$broadcast(AUTH_EVENTS.notAuthorized,
                                          response);
                }
                if (response.status === 419 || response.status === 440) {
                    //Session has expired
                    $rootScope.$broadcast(AUTH_EVENTS.sessionTimeout,
                                          response);
                }
                return $q.reject(response);
            }
        };
    })
// register the interceptor as a service, intercepts ALL angular ajax http calls
    .factory('myHttpInterceptor', function ($q, $window) {

        return function (promise) {
            return promise.then(function (response) {
                // do something on success
                // todo hide the spinner
                //$("#site_statistics_loading").hide();
                return response;

            }, function (response) {
                // do something on error
                // todo hide the spinner
                //$("#site_statistics_loading").hide();
                return $q.reject(response);
            });
        };
    });

window.app.directive('inputMask', function () {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, ctrl) {
            if (attrs.ngType == 'phone') {
                $(el).inputmask(scope.$eval(attrs.inputMask));
            }
            else if (attrs.ngType == 'currency' || attrs.ngType == 'decimal') {
                $(el).inputmask('decimal', {
                    rightAlignNumerics: false
                    //numericInput: true,
                    // rightAlignNumerics: true,
                    // greedy: false
                    //999,999,999.99
                });
            }
            $(el).on('change', function (e) {
                if (attrs.ngType == 'phone') {
                    scope.$eval(attrs.ngModel + "='" + (el.val().replace(/[^\d]/g, '')) + "'");
                }
                else if (attrs.ngType == 'decimal') {
                    scope.$eval(attrs.ngModel + "=" + parseFloat(el.val().replace(/[^\d\.]/g, '')) + "");
                    scope.$apply();
                }
                else if (attrs.ngType == 'currency' || attrs.ngType == 'decimal') {
                    var value = el.val().replace(/[^\d\.\-]/g, '');
                    if (value == NaN) { value = 0; }
                    //$(el).val(value);
                    scope.$eval(attrs.ngModel + "=" + value + "");
                    scope.$apply();
                }
            });
        }
    };
});
//driective for paging table 
window.app.directive('pagingTable', function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, el, attrs, ctrl) {
            //registry for table 
            var oTable = $(el).dataTable({
                "aoColumns": scope.$eval("aoColumns"),
                "aoColumnDefs": scope.$eval("aoColumnDefs"),
                "aaSorting": [[1, 'asc']],
                "aLengthMenu": [
                   [5, 15, 20, -1],
                   [1, 2, 5, 15, 20, "All"] // change per page values here
                ],
                // set the initial value
                "iDisplayLength": 10,
                "fnCreatedRow": function (nRow, aData, iDataIndex) {
                    ($compile(nRow)(scope)[0].innerHTML);// $compile(nRow)(scope);
                },
            });

            // watch for any changes to our data, rebuild the DataTable
            scope.$watch(attrs.aaData, function (value) {
                var val = value || null;
                if (val) {
                    oTable.fnClearTable();
                    oTable.fnAddData(scope.$eval(attrs.aaData));
                }
            });

        }
    };
}) 